package top.yehot.cmmu.swagger.config;

import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.http.MediaType;
import org.springframework.web.reactive.function.server.RequestPredicates;
import org.springframework.web.reactive.function.server.RouterFunction;
import org.springframework.web.reactive.function.server.RouterFunctions;
import org.springframework.web.reactive.function.server.ServerResponse;

import top.yehot.cmmu.swagger.support.SwaggerProvider;
import top.yehot.cmmu.swagger.support.SwaggerResourceHandler;

@ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.REACTIVE)
public class GatewaySwaggerAutoConfiguration {
	
	@Bean
	public SwaggerProvider swaggerProvider(SwaggerProperties swaggerProperties) {
		return new SwaggerProvider(swaggerProperties);
	}
	
	@Bean
	public SwaggerResourceHandler swaggerResourceHandler(SwaggerProvider swaggerProvider) {
		return new SwaggerResourceHandler(swaggerProvider);
	}
	
	@Bean
	public RouterFunction<?> swaggerRouterFunction(SwaggerProperties swaggerProperties, SwaggerResourceHandler swaggerResourceHandler) {
		if (swaggerProperties.getEnabled()) {
			return RouterFunctions
					.route(
							RequestPredicates.GET("/swagger-resources").and(RequestPredicates.accept(MediaType.ALL)),
							swaggerResourceHandler);
		} else {
			// 关闭时，返回404
			return RouterFunctions
					.route(
							RequestPredicates.GET("/swagger-ui/**").and(RequestPredicates.accept(MediaType.ALL)),
							serverRequest -> ServerResponse.notFound().build())
					.andRoute(
							RequestPredicates.GET("/*/v2/api-docs").and(RequestPredicates.accept(MediaType.ALL)),
							serverRequest -> ServerResponse.notFound().build());
		}
		
	}
	
}
